package com.mxsoft.concurrent;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;

public class SemaphoreDemo {
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(1);

        CountDownLatch countDownLatch = new CountDownLatch(10);

        for (int i = 0; i < 10; i ++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {

                        countDownLatch.await();
                        semaphore.acquire();

                        System.out.println(Thread.currentThread().getName() + " 获得了资源  开始执行任务");
                        Thread.sleep(5000);
                        System.out.println(Thread.currentThread().getName() + " 获得了资源  结束执行任务");

                        semaphore.release();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();

            countDownLatch.countDown();
        }
    }
}
